'use strict';

const Controller = require('egg').Controller;

class StockController extends Controller {
  constructor(ctx) {
    super(ctx);
    this.root = 'http://127.0.0.1:7001/api/v1';
  }

  async request(url, opts) {
    url = `${this.root}${url}`;
    console.log(url);
    opts = Object.assign({
      timeout: [ '30s', '30s' ],
      dataType: 'json',
    }, opts);
    return this.ctx.curl(url, opts);
  }

  async test(p) {
    //await this.userRegister();
    await this.userLogin();
  }

  checkSuccess(result) {
    console.log(result);
    if (result.status !== 200 && result.status !== 201) {
      const errorMsg = result.data && result.data.msg ? result.data.msg : 'unknown error';
      this.ctx.throw(result.status, errorMsg);
    }

    // if (!result.data.success) {
    //   this.ctx.throw(500, 'remote response error', { data: result.data });
    // }

    this.ctx.body = { data: result.data };
    this.ctx.status = result.status;
  }

  async userRegister() {
    const params = {
      'username': "test12",
      'password': '123456'
    }
    const result = await this.request('/user', {
      method: 'post',
      data: params,
      contentType: 'json',
    });

    //console.log(result);
    this.checkSuccess(result);
  }

  async userLogin() {
    const params = {
      'username': "test2",
      'password': '123456'
    }
    const result = await this.request('/user/login', {
      method: 'post',
      data: params,
      contentType: 'json',
    });

    //console.log(result);
    this.checkSuccess(result);
  }
}


module.exports = StockController;
